const input = document.querySelector('#image-input');

let _onImageSelected;

// 读取图片文件信息
const readFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      resolve(event.target.result);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  })
};

// 将图片文件转换为 Image 对象
const generateImage = (image) => {
  return new Promise((resolve, reject) => {
    const imageElement = document.createElement('img');
    imageElement.onload = () => {
      resolve(imageElement);
    };
    imageElement.onerror = reject;
    imageElement.src = image;
  });
};

// 监听文件选择
input.addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const fileDataUrl = await readFile(file);
  const imageElement = await generateImage(fileDataUrl);
  _onImageSelected && _onImageSelected(imageElement);
});

export const setOnImageSelected = (onImageSelected) => {
  _onImageSelected = onImageSelected;
};
